<!--
  Author wln
  Version 1.0.0
  Date 2020年11月23日15:15:17
  Desc 表格组件 适用于简单的表格
  Tip * 使用说明 readme.md
-->
<template>
    <div>
        <el-form
                :inline="true"
                size="mini"
                class="topLine-search-form"
                v-if="showSearch"
        >
            <el-row style="margin-top: 10px;">
                <el-col v-for="item in tableData.data"
                        v-if="item.isSearch"
                        :xl="item.xl || getColNnm('xl',item.type)"
                        :span="item.span || getColNnm('span',item.type)"
                >
                    <el-form-item :label="item.label" v-if="item.type === 'input'">
                        <el-input
                                v-model="query[item.searchKey]"
                                :placeholder="'请输入' + item.label"
                        ></el-input>
                    </el-form-item>

                    <el-form-item :label="item.label" v-if="item.type === 'int'">
                        <el-input
                                v-model="query[item.searchKey]"
                                :placeholder="'请输入' + item.label"
                                @input="handleInput(item.searchKey,item.type,item.negative || false)"
                        />
                    </el-form-item>

                    <el-form-item :label="item.label" v-if="item.type === 'float'">
                        <el-input
                                v-model="query[item.searchKey]"
                                :placeholder="'请输入' + item.label"
                                @input="handleInput(item.searchKey,item.type,item.negative || false)"
                        />
                    </el-form-item>

                    <el-form-item :label="item.label" v-if="item.type === 'select'">
                        <el-select
                                v-if="item.list"
                                v-model="query[item.searchKey]"
                                :placeholder="'请选择' + item.label"
                                filterable
                        >
                            <el-option
                                    v-for="selectItem in item.list"
                                    :key="selectItem.value"
                                    :label="selectItem.label"
                                    :value="selectItem.value"
                            >
                            </el-option>
                        </el-select>
                        <div v-else style="color: red">需传入list</div>
                    </el-form-item>

                    <el-form-item :label="item.label" v-if="item.type === 'cascader'">
                        <el-cascader
                                v-if="item.list"
                                v-model="query[item.searchKey]"
                                :options="item.list"
                                filterable
                                :disabled="item.disabled || false"
                                expandTrigger="hover"
                                :props="{ checkStrictly: true,expandTrigger: 'hover' }"
                                :show-all-levels="true"
                                @change="cascader"
                        />
                        <div v-else style="color: red">需传入list</div>
                    </el-form-item>

                    <el-form-item :label="item.label" v-if="item.type === 'date'">
                        <el-date-picker
                                v-model="query[item.searchKey]"
                                type="date"
                                :placeholder="'请选择' + item.label"

                                :value-format="item.format || 'yyyy-MM-dd'"
                                :format="item.format || 'yyyy-MM-dd'"
                        >
                        </el-date-picker>
                    </el-form-item>

                    <el-form-item :label="item.label" v-if="item.type === 'dateTime'">
                        <el-date-picker
                                v-model="query[item.searchKey]"
                                type="datetime"
                                :placeholder="'请选择' + item.label"
                                :value-format="item.format || 'yyyy-MM-dd HH:mm:ss'"
                                :format="item.format || 'yyyy-MM-dd HH:mm:ss'"
                        >
                        </el-date-picker>
                    </el-form-item>

                    <el-form-item :label="item.label" v-if="item.type === 'time'">
                        <el-time-picker
                                v-model="query[item.searchKey]"
                                :placeholder="'请选择' + item.label"
                                :value-format="item.format || 'HH:mm:ss'"
                                :format="item.format || 'HH:mm:ss'"
                        >
                        </el-time-picker>
                    </el-form-item>

                    <el-form-item :label="item.label" v-if="item.type === 'dateTimeRange'">
                        <!-- 默认以开始时间为默认值，提交/重置时特殊处理 -->
                        <el-date-picker
                                v-model="query[item.searchKey[0]]"
                                type="datetimerange"
                                :value-format="item.format || 'yyyy-MM-dd HH:mm:ss'"
                                :format="item.format || 'yyyy-MM-dd HH:mm:ss'"
                                range-separator="至"
                                start-placeholder="开始时间"
                                end-placeholder="结束时间"
                        />
                    </el-form-item>

                    <el-form-item :label="item.label" v-if="item.type === 'dateRange'">
                        <el-date-picker
                                v-model="query[item.searchKey[0]]"
                                type="daterange"
                                :value-format="item.format || 'yyyy-MM-dd'"
                                :format="item.format || 'yyyy-MM-dd'"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                        />
                    </el-form-item>

                    <el-form-item :label="item.label" v-if="item.type === 'timeRange'">
                        <el-time-picker
                                is-range
                                v-model="query[item.searchKey[0]]"
                                :value-format="item.format || 'HH:mm:ss'"
                                :format="item.format || 'HH:mm:ss'"
                                range-separator="至"
                                start-placeholder="开始时间"
                                end-placeholder="结束时间"
                        />
                    </el-form-item>
                </el-col>

                <el-col :xl="3" :span="4">
                    <el-button
                            type="primary"
                            size="mini"
                            @click="searchList"
                            :style="{marginTop: searchBtnTop + 'px'}"
                    >搜索
                    </el-button>
                    <el-button
                            size="mini"
                            plain
                            @click="resetList"
                            :style="{marginTop: searchBtnTop + 'px'}"
                    >重置
                    </el-button>
                </el-col>
            </el-row>
        </el-form>

        <el-row class="table-int">
            <el-col :span="12">
                <svg-icon icon-class="excel"/>
                <span class="title">{{tableData.name || '数据列表'}}</span>
            </el-col>
            <el-col :span="12" class="btn-group">
                <slot name="businessHandle"></slot>
            </el-col>
        </el-row>
        <el-table
                border
                v-loading="loading"
                :data="data"
                style="width: 100%;margin-top: 10px;"
                size="mini"
                @selection-change="handleSelectionChange"
        >
            <slot name="Checkbox"></slot>
            <el-table-column label="序号" v-if="tableData.index" width="55">
                <template slot-scope="scope">
                    {{(query.page - 1) * query.pageSize + scope.$index + 1}}
                </template>
            </el-table-column>
            <el-table-column
                    v-for="item in tableData.data"
                    v-if="item.isTable !== false"
                    :label="item.label"
                    :prop="item.prop"
                    :width="item.width ? item.width : 'auto'"
            >
                <template slot-scope="scope">
					<span v-if="item.backList">
						{{ item.backList[scope.row[item.prop]] }}
					</span>
                    <span v-else-if="item.isJoin && item.connector">
						{{ scope.row[item.prop.split(',')[0]] + item.connector + scope.row[item.prop.split(',')[1]]}}
					</span>
                    <span v-else>
						{{ scope.row[item.prop] }}
					</span>
                </template>
            </el-table-column>
            <slot name="tableHandle"></slot>
        </el-table>
        <Pagination
                v-if="total > 0&&showPagination"
                :page.sync="query.page"
                :limit.sync="query.pageSize"
                :total="total"
                style="margin-top: 0;padding: 30px 0;text-align: right"
                @pagination="getList"
        >
        </Pagination>
    </div>
</template>

<script>
  export default {
    name: 'BcTable',
    props: {
      tableData: Object,
      showSearch: {
        type: Boolean,
        default: true
      },
      showPagination: {
        type: Boolean,
        default: true
      },
      searchBtnTop: {
        type: Number,
        default: 33
      }
    },
    data() {
      return {
        query: {},
        data: [],
        loading: false,
        total: 0,
        Did: '',
        modelValue: [],
        newList: [],
        newList2: [],
        multipleSelection: []
      }
    },
    watch: {
      // 监听查询参数变化，重置表单
      tableData: {
        handler: function(val) {
            this.dealQuery()
            this.resetList()
        },
        deep: true
      }
    },
    activated(){
      setTimeout(()=>{
        this.dealQuery()
        this.getList()
      },500)
    },
    created() {
      setTimeout(()=>{
        this.dealQuery()
        this.getList()
      },500)
    },
    methods: {
      // 处理查询信息
      dealQuery() {
        // 注 ： 这里不能用计算属性， 计算的根数据为tableData, input 输入时根数据并未修改，修改input 数据不会变化
        let query = {
          page: 1,
          pageSize: this.tableData.pageSize || 10
        }
        this.tableData.data.forEach(item => {
          if ((item.isSearch || item.isParam) && item.searchKey) {
            if (item.isParam) {
              query[item.searchKey] = item.value || ''
              return
            }
            if (typeof item.searchKey == 'string') {
              query[item.searchKey] = ''
            } else {
              if (item.type == 'timeRange') {
                item.searchKey.forEach(sitem => {
                  query[sitem] = ''
                })
              } else {
                item.searchKey.forEach(sitem => {
                  query[sitem] = []
                })
              }
            }
          }
        })
        this.query = query
      },
      // 处理栅格
      getColNnm(media, type) {
        let arr = ['dateRange', 'timeRange', 'dateTimeRange', 'numRange']
        if (media == 'xl') {
          if (arr.includes(type)) {
            return 6
          }
          return 3
        } else {
          if (arr.includes(type)) {
            return 8
          }
          return 4
        }
      },
      // 获取数据
      getList() {
        this.loading = true
        let data = JSON.parse(JSON.stringify(this.query))
        this.tableData.data.forEach(item => {
          if (item.searchKey) {
            if (item.isParam) {
              if (item.type != 'cascader') {
                data[item.searchKey] = item.value || ''
                return
              }
            }
            if (item.type == 'cascader' && item.list.length > 0) {
              // 级联选择器 注：传最后一个值的id
                data[item.searchKey] = data[item.searchKey][data[item.searchKey].length - 1]
            } else if (typeof item.searchKey == 'object' && item.searchKey.length > 0) {
              // 日期/时间区间选择器
              let currentData = data[item.searchKey[0]]
              data[item.searchKey[0]] = !currentData[0] || currentData[0] == [] ? '' : currentData[0]
              data[item.searchKey[1]] = !currentData[1] || currentData[1] == [] ? '' : currentData[1]
            }
          }
        })
        for (let k in data) {
          if (!data[k]) {
            delete data[k]
          }
        }

        this.tableData.method(data).then(res => {
          if (res.flag) {
            this.data = res.data.items
            this.total = res.data.total
          }
          this.loading = false
        }).catch(err => {
          this.loading = false
        })
      },
      // 处理三级联动数据
      cascader(val) {
        this.modelValue = val
      },
      dg(dataList, dpdId) {
        if (dpdId == dataList[0].pid) {
          for (const i in dataList) {
            dataList[i].disabled = false
            if (dataList[i].children) {
              for (let j in dataList[i].children) {
                this.dg(dataList[i].children, dataList[i].children[j].value)
              }
            }
          }
        } else {
          for (let i in dataList) {
            if (dataList[i].value == dpdId) {
              dataList[i].disabled = false
              if (dataList[i].children) {
                for (const j in dataList[i].children) {
                  this.dg(dataList[i].children, dataList[i].children[j].value)
                }
              }
            } else {
              if (dataList[i].children) {
                for (const j in dataList[i].children) {
                  this.dg(dataList[i].children, dpdId)
                }
              }
            }
          }
        }
        return dataList
      },

      // 搜索
      searchList() {
        this.query.page = 1
        this.getList()
      },

      // 重置
      resetList() {
        for (let k in this.query) {
          if (k != 'page' && k != 'pageSize') {
            this.tableData.data.forEach(item => {
              if (item.searchKey) {
                if (typeof item.searchKey == 'string') {
                  if (item.searchKey && item.searchKey == k) {
                    this.query[k] = ''
                  }
                } else {
                  item.searchKey.forEach(sitem => {
                    this.query[sitem] = ''
                  })
                }
              }
            })
          }
        }
        this.query.page = 1
        this.getList()
      },

      // 输入数字
      handleInput(key, type, negative) {
        if (type == 'float') {
          if (negative) {
            this.query[key] = this.query[key].replace(/(?!^)\-|(?!^)[^\d\.]/g, '')
            this.query[key] = this.query[key].replace(/[^\d\-\.]/g, '')
          } else {
            this.query[key] = this.query[key].replace(/[^\d\.]/g, '')
          }
        } else if (type == 'int') {
          if (negative) {
            this.query[key] = this.query[key].replace(/(?!^)\-|(?!^)[^\d]/g, '')
            this.query[key] = this.query[key].replace(/[^\d\-]/g, '')
          } else {
            this.query[key] = this.query[key].replace(/[^\d]/g, '')
          }
        }
      },
      // 多选
      handleSelectionChange(val) {
        this.multipleSelection = val
      }
    }
  }
</script>

<style lang="scss" scoped>
    /deep/ .el-textarea {
        textarea {
            height: 100%;
        }
    }

    .el-form /deep/ .el-col {
        height: 80px;
    }

    .table-int {
        font-size: 18px;
        color: #333;
        margin: 10px 0 15px;
        line-height: 28px;

        .title {
            font-weight: 700;
            color: #333;
            display: inline-block;
            margin-left: 5px;
        }

        .btn-group {
            text-align: right;
        }
    }

</style>
